package org.petstore.web.servlet;

import com.alibaba.fastjson.JSON;
import org.petstore.domain.Account;
import org.petstore.service.AccountService;
import org.petstore.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UsernameExistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*String username=req.getParameter("username");
        AccountService accountService=new AccountService();
        Account result=accountService.getAccount(username);

        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();

        Result result1=new Result();

        if(result==null){
            //用户名可用
            result1.setCode(0);
            result1.setMsg("Not Exist");
        }else{
            //用户名不可用
            result1.setCode(1);
            result1.setMsg("Exist");
        }

        String str= JSON.toJSONString(result1);
        out.print(str);
        out.flush();
        out.close();*/
        resp.setContentType("text/json");//以json形式输出
        PrintWriter out=resp.getWriter();
        String username = req.getParameter("username");
        Result result1=new Result();
        if(username==null||username.equals(""))
        {
            //用户名未输入
            result1.setCode(2);
            result1.setMsg("null");
        } else{
            AccountService accountService=new AccountService();
            Account result = accountService.getAccount(username);
            //resp.setContentType("text/plain");//作为字符串输出
            if(result==null)
            {
                //用户名可用
                result1.setCode(1);
                result1.setMsg("Not Exist");
                //out.print("Not Exist");
            }else{
                //用户名不可用
                result1.setCode(0);
                result1.setMsg("Exist");
                //out.print("Exist");
            }
        }
        String str = JSON.toJSONString(result1);
        out.print(str);
        out.flush();
        out.close();
    }
}
